package com.xiaolong.websocket.core;

import io.netty.channel.Channel;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;

import java.util.concurrent.ConcurrentHashMap;

public class NettyManager {

    public static AttributeKey<String> TOKEN = AttributeKey.valueOf("token");

    public static AttributeKey<Long> UID = AttributeKey.valueOf("uid");

    private static final ConcurrentHashMap<Long, Channel> userToChannelMap = new ConcurrentHashMap<>();

    private static final ConcurrentHashMap<Channel, Long> channelToUserMap = new ConcurrentHashMap<>();

    public static <T> void setAttr(Channel channel, AttributeKey<T> attributeKey, T data) {
        Attribute<T> attr = channel.attr(attributeKey);
        attr.set(data);
    }

    public static <T> T getAttr(Channel channel, AttributeKey<T> ip) {
        return channel.attr(ip).get();
    }

    public static void addChannel(Long userId, Channel channel) {
        userToChannelMap.put(userId, channel);
        channelToUserMap.put(channel, userId);
    }

    public static Channel getChannel(Long userId) {
        return userToChannelMap.get(userId);
    }

    public static Long getUserId(Channel channel) {
        return channelToUserMap.get(channel);
    }

    public static void removeChannel(Long userId) {
        Channel channel = userToChannelMap.remove(userId);
        if (channel != null) {
            channelToUserMap.remove(channel);
        }
    }

    public static void removeChannel(Channel channel) {
        Long userId = channelToUserMap.remove(channel);
        if (userId != null) {
            userToChannelMap.remove(userId);
        }
    }

    public static boolean hasUser(Long userId) {
        return userToChannelMap.containsKey(userId);
    }

    public static boolean hasChannel(Channel channel) {
        return channelToUserMap.containsKey(channel);
    }
}